package com.itheima.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.RecommendMovement;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

//从redis中读取推荐的动态插入的mongo中
@Component
public class MovementJob {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void recommend() {
        System.out.println("开始动态推荐");
        Set<String> keys = stringRedisTemplate.keys("QUANZI_PUBLISH_RECOMMEND_*");
        if (CollectionUtil.isNotEmpty(keys)) {
            for (String key : keys) {
                key = key.replaceAll("QUANZI_PUBLISH_RECOMMEND_", "");//获取推荐的用户id

                //清空原来推荐给此用户的数据
                mongoTemplate.remove(new Query(Criteria.where("userId").is(Long.valueOf(key))), RecommendMovement.class);

                //保存数据
                String s = stringRedisTemplate.opsForValue().get("QUANZI_PUBLISH_RECOMMEND_" + key);
                if (StringUtils.isNotEmpty(s)) {
                    String[] pidArr = s.split(",");
                    for (String pid : pidArr) {
                        RecommendMovement recommendMovement = new RecommendMovement();
                        recommendMovement.setCreated(System.currentTimeMillis());
                        recommendMovement.setUserId(Long.valueOf(key));//用户id
                        recommendMovement.setPid(Long.valueOf(pid));
                        Query query = new Query(Criteria.where("pid").is(Long.valueOf(pid)));
                        Movement movement = mongoTemplate.findOne(query, Movement.class);
                        recommendMovement.setPublishId(movement.getId());
                        recommendMovement.setScore(RandomUtil.randomDouble(60, 90));
                        mongoTemplate.save(recommendMovement);
                    }


                }
            }
        }

        System.out.println("结束动态推荐");
    }
}